package edu.pku.sei.transformation.atl.action;

import java.io.FileWriter;
import java.io.IOException;

import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import edu.pku.sei.transformation.atl.adapter.ATLModuleAdapter;
import edu.pku.sei.transformation.atl.codegen.ATLGenerator;
import edu.pku.sei.transformation.atl.rule.IATLModule;
import edu.pku.sei.transformation.editor.model.execution.TransformationExecution;
import edu.pku.sei.transformation.editor.views.icons.IconsProvider;
import edu.pku.sei.transformation.editor.views.problem.ProblemView;

public class GenATLCodeAction extends Action {
	TransformationExecution transExecution = null;
	IATLModule module = null;

	public GenATLCodeAction(Object selectedElement) {
		setText("generate ATL code");
		setImageDescriptor(IconsProvider
				.getImageDescriptor(IconsProvider.FILE_EXPORT_ICO));
		if (selectedElement instanceof TransformationExecution)
			transExecution = (TransformationExecution) selectedElement;
	}
	
	@Override
	public boolean isEnabled() {
		if (transExecution != null)
			return true;
		else
			return false;
	}
	
	@Override
	public void run() {
		ProblemView.clearMarks(transExecution.getModel());
		ProblemView.showView();
		try {
			module = new ATLModuleAdapter(transExecution);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
				.getShell();
		FileDialog dialog = new FileDialog(shell, SWT.SAVE);
		dialog.setFileName(module.getHeader().getName() + ".atl");
		String addr = dialog.open();
		if (addr == null)
			return;
		ATLGenerator generator = new ATLGenerator();
		String content = generator.generate(module);

		FileWriter fw;
		try {
			fw = new FileWriter(addr);
			fw.write(content, 0, content.length());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
